package pdd.netty.Handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.util.Locale;

/**
 * @author:liyangpeng
 * @date:2020/1/14 15:16
 */
public class WebScoketFramHadler extends SimpleChannelInboundHandler<WebSocketFrame> {

    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        //文本消息处理
        if (frame instanceof TextWebSocketFrame) {
            String request = ((TextWebSocketFrame) frame).text();
            ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase(Locale.US)));
        //二进制数据处理
        }else if(frame instanceof  BinaryWebSocketFrame){
            BinaryWebSocketFrame binaryWebSocketFrame = ((BinaryWebSocketFrame)frame);
            ByteBuf content = binaryWebSocketFrame.content();
            byte [] bytes=new byte[content.capacity()];
            content.readBytes(bytes);
//            String result=new String(bytes,"UTF-8");
//            System.out.println(result);
            ByteBuf byteBuf = Unpooled.directBuffer(content.capacity());
            byteBuf.writeBytes(bytes);
            ctx.writeAndFlush(new BinaryWebSocketFrame(byteBuf));
            //不支持的数据格式
        } else {
            String message = "unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }
}
